<template>
    <div class="page-indexlist">
        <div class="page-indexlist-wrapper">
            <mt-index-list>
                <mt-index-section v-for="(area, index) in phones" :key="index" :index="area.initial">
                    <mt-cell v-for="(people, index) in area.cells" :key="index" @click.native="showCall(people)" :title="people.name"></mt-cell>
                </mt-index-section>
            </mt-index-list>
        </div>
        <actionsheet v-model="callAction" :menus="callMenu" @on-click-menu="onCall" @on-click-menu-delete="onDelete" show-cancel></actionsheet>
    </div>
</template>
<style>
@component-namespace page {
    @component indexlist {
        @descendent desc {
            text-align: center;
            color: #666;
            padding-bottom: 5px;
        }
        @descendent wrapper {
            width: 100%;
            border-top: solid 1px #ddd;
        }
    }
}

.mint-indexlist-navitem {
    height: 18px;
}
</style>
<script>
import Vue from 'vue';
import Mint from 'mint-ui';
import 'mint-ui/lib/style.css';
import {
    Toast,
    Actionsheet
} from 'vux'

Vue.use(Mint);

import api from '../api';

import {
    mapState,
    mapActions
} from 'vuex'

let phones = [{
    "name": "马云",
    "phone": "",
    "camelChars": "MY",
    "fullChars": "MaYun"
}, {
    "name": "马化腾",
    "phone": "",
    "camelChars": "MHT",
    "fullChars": "MaHuaTeng"
}, {
    "name": "李彦宏",
    "phone": "",
    "camelChars": "LYH",
    "fullChars": "LiYanHong"
}];
export default {
    components: {
        Toast,
        Actionsheet

    },
    computed: {
        ...mapState({
            phonesApp: state => state.z43.phonesApp,
            phones: state => state.z43.phones,
            isLoading: state => state.vux.isLoading,
            uid: state => state.vux.uid
        })
    },
    data() {
        return {
            // phones: [],
            numbers: [],
            peoDic: {},
            hasData: false,
            callAction: false,
            callMenu: [{
                    label: '拨打?<br/><span style="color:#666;font-size:12px;">您正在拨打给.</span>',
                    type: '<span style="color:red">Delete</span>'
                }, {
                    label: '录音拨打',
                    type: 'primary',
                    value: 'luyin'
                },
                 {
                    label: '不录显号',
                    value: 'noRecord'
                }, {
                    label: '直接拨打',
                    value: 'system'
                }
            ],
            calltar: {
                name: "test"
            }
        };
    },
    watch: {
        // "$route": function() {
        //     if (this.$route.path == '/m_contacts' && !this.hasData) this.getPhones();
        // },
        "uid": function() {
            if (!this.hasData) this.getPhones();
        },
        "phonesApp":function(){
            this.check2save();
        }
    },
    methods: {
        onCall(key) {
            console.log(key + " " + this.calltar.phone);
            // this.call(this.calltar);
        },
        onDelete() {
            this.showSuccess = true
        },
        showCall(tar) {
            this.calltar = tar;
            if (this.calltar.phone.length == 0) {
                let title, content;
                if (!isApp) {
                    title = '您正在拨打给"' + this.calltar.name + '"';
                    content: '下载App自动导入通讯录后使用';
                } else {
                    title = '您正在拨打给"' + this.calltar.name + '"';
                    content: '请登录后使用';
                }
                this.$vux.confirm.show({
                    title: title,
                    content: content,
                    onShow() {
                        console.log('plugin show')
                    },
                    onHide() {
                        console.log('plugin hide')
                    },
                    onCancel() {
                        console.log('plugin cancel')
                    },
                    onConfirm() {
                        if (isApp) {
                            this.go("login");
                        } else {

                        }
                        console.log('app下载页面跳转!')
                    }
                })
                return;
            }
            this.callMenu[0].label = '拨号?<br/><span style="color:#666;font-size:12px;">您正在拨打给 </span><span style="color:#666;font-size:14px;font-weight:bold;">' + this.calltar.name + '.</span>';
            this.callAction = true;
            console.log(tar);
        },
        call(tar) {
            let _this = this;
            api.call({
                uid: this.uid,
                pid2: tar.pid,
                call: tar.phone,
                name2: tar.name
            }).then(data => {
				if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                
				data = data.data;
				this.$vux.toast.show({
					text: "呼叫成功",
					type: 'success'
				})
                
            })
        },
        getPhones(refresh) {  //refresh添加电话后重新刷新
            let _this = this;
            if (this.hasData && !refresh)return; // 已有数据
            if (!this.uid) return this.refresh(); //显示默认数据. 跳出获取用户信息逻辑
            
            this.$store.commit('updateLoadingStatus', {isLoading: true});
            api.phones().then(data => {
                if (data && data.errno == 0) {
                    data = data.data;
                    let temp = [],
                        item, peo;
                    _this.peoDic = {}; //清空字典
                    for (var i = data.length - 1; i >= 0; i--) {
                        item = data[i];
                        try {
                            peo = {
                                name: item.name || item.nname,
                                phone: item.phone,
                                pid: item.pid,
                                "camelChars": pinyin.getCamelChars(item.name || item.nname).toUpperCase(),
                                "fullChars": pinyin.getFullChars(item.name || item.nname)
                            };
                            temp.push(peo);
                            _this.peoDic[item.phone] = peo;
                        } catch (e) {
                            console.log(e);
                            continue;
                        }
                    };
                    _this.check2save();
                    // _this.numbers = temp;  //暂未使用
                    this.refresh(temp);
                    // console.log(data);
                } else { //发生错误.
                    this.$store.commit('updateLoadingStatus', {isLoading: false});
                    this.refresh(); //显示默认数据.
                    this.$vux.toast.show({text: data.errmsg,type: 'warn'})
                    console.log(data.errmsg);
                }
            })
        },
        check2save() {
            let tempPhones ;
            try { //是否app已有通讯录数据判断;
                tempPhones = this.phonesApp.length>0?this.phonesApp:phonesApp ;
                if (!tempPhones || tempPhones.length == 0) return;
            } catch (e) {
                return;
            }
            var item, temp = [];
            for (var i = tempPhones.length - 1; i >= 0; i--) {
                item = tempPhones[i];
                if (this.peoDic[item.phone] == undefined) temp.push(item);
            };
            let _this = this;
            if (temp.length > 0) {
                this.$store.commit('updateLoadingStatus', {isLoading: true});
                api.friendsAdd({
                    phones: temp
                }).then(data => {
                    if (data && data.errno == 0) {
                        data = data.data;
                        _this.$vux.toast.show({text: "号码保存成功",type: 'success'})
                        this.$store.commit('updateLoadingStatus', {isLoading: false});
                        this.getPhones(true); //重新请求数据并刷新
                    } else { //发生错误.                    
                        _this.$vux.toast.show({ext: data.errmsg,type: 'warn'})
                    }
                })
            }
        },
        refresh(items) {
            console.log("refresh");
            if (!items || items.length == 0) {
                items = phones;
                this.hasData = false;
            } else {
                this.hasData = true;
            }
            let temp = [];
            var item;
            for (var i = items.length - 1; i >= 0; i--) {
                item = items[i];
                item.label = item.name;
                item.value = item.fullChars;
            };
            // this.phones = [];
            'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').forEach(initial => {
                let cells = items.filter(phone => phone.camelChars[0] === initial);
                if (cells.length > 0) {
                    temp.push({
                        initial,
                        cells
                    });
                }
            });
            this.$store.commit("z43/setPhones", temp);

            this.$store.commit('updateLoadingStatus', {
                isLoading: false
            });
        }
    },
    mounted() {
        // this.refresh(phones);
        this.getPhones();
    },
    created() {
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        let listH = h - 50; // 53;
        setTimeout(function() {
            let list = document.querySelector(".page-indexlist .mint-indexlist-content");
            list.style.height = listH + "px";
        }, 10)
    }
};
</script>
